<template>
  <div>
    <!-- 面包屑到导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只能为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <el-row class="catopt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedCates"
            :options="cateList"
            :props="cascaderProps"
            @change="selectHandleChange"
            clearable
            class="cascader"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isbtnDisable"
            size="mini"
            @click="showManyParamsDialog"
            >添加参数</el-button
          >
          <!-- 动态属性表 -->
          <el-table :data="manyTableData" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleTagClosed(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 输入按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 添加属性</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditParamsDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParamsById(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isbtnDisable"
            size="mini"
            @click="showOnlyParamsDialog"
            >添加属性</el-button
          >
          <!-- 静态态属性表 -->
          <el-table :data="onlyTableData" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleTagClosed(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 输入按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 添加属性</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditParamsDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParamsById(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 动态参数弹框 -->
    <el-dialog
      title="添加参数"
      :visible.sync="manyDialogVisible"
      width="50%"
      @close="paramsManyClosed"
    >
      <el-form
        :model="paramsManyForm"
        :rules="paramsManyRules"
        ref="paramsManyFormRef"
        label-width="100px"
      >
        <el-form-item label="参数名称" prop="attr_name">
          <el-input v-model="paramsManyForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="manyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addManyParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 静态参数弹框 -->
    <el-dialog
      title="添加属性"
      :visible.sync="onlyDialogVisible"
      width="50%"
      @close="paramsOnlyClosed"
    >
      <el-form
        :model="paramsOnlyForm"
        :rules="paramsOnlyRules"
        ref="paramsOnlyFormRef"
        label-width="100px"
      >
        <el-form-item label="属性名称" prop="attr_name">
          <el-input v-model="paramsOnlyForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="m = onlyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOnlyParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑修改参数弹框 -->
    <el-dialog
      title="修改属性"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editParamsClosed"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsRules"
        ref="editParamsFormRef"
        label-width="100px"
      >
        <el-form-item label="修改参数" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="m = editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsDate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      // 下拉框的props属性
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 被选中的数据下拉框
      selectedCates: [],
      // 激活那个面板
      activeName: 'many',
      // 动态参数
      manyTableData: [],
      // 静态属性参数
      onlyTableData: [],
      // 动态属性添加框的弹出与否
      manyDialogVisible: false,
      // 静态属性添加框的弹出与否
      onlyDialogVisible: false,
      // 修改对话框
      editDialogVisible: false,
      // 校验规则
      paramsManyForm: {
        attr_name: '',
      },
      paramsManyRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      // 编辑框绑定数据
      editParamsForm: {
        attr_name: '',
      },
      editParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      paramsOnlyForm: {
        attr_name: '',
      },
      paramsOnlyRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      inputVisible: false,
      inputValue: ''
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: {},
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取商品分类失败')
      }
      this.cateList = res.data
    },
    selectHandleChange() {
      // 不是三级分类
      this.getParamsData()
    },
    // tabs页标签点击事件
    handleClick() {
      this.getParamsData()
    },
    // 获取参数的列表数据
    async getParamsData() {
      if (this.selectedCates.length !== 3) {
        // 父级分类的id
        this.selectedCates = []
        this.manyTableData = []
        this.onlyTableData = []
        return false
      }
      // 三级菜单
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('获取列表参数失败')
      }
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 添加字段，
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 弹出添加属性与参数的对话框
    showManyParamsDialog() {
      this.manyDialogVisible = true
    },
    // 弹出添加属性与参数的对话框
    showOnlyParamsDialog() {
      this.onlyDialogVisible = true
    },
    // 动态关闭初始化表单
    paramsManyClosed() {
      this.$refs.paramsManyFormRef.resetFields()
    },
    // 静态关闭表单初始化
    paramsOnlyClosed() {
      this.$refs.paramsOnlyFormRef.resetFields()
    },
    // 添加参数提交值服务器
    addManyParams() {
      this.$refs.paramsManyFormRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.paramsManyForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) {
          this.$message.error('添加参数错误')
        }
        this.$message.success('添加成功')
        this.manyDialogVisible = false
        this.getParamsData()
      })
    },
    addOnlyParams() {
      this.$refs.paramsOnlyFormRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.paramsOnlyForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) {
          this.$message.error('添加参数错误')
        }
        console.log(res)
        this.$message.success('添加成功')
        this.onlyDialogVisible = false
        this.getParamsData()
      })
    },
    // 编辑操作弹出对话框
    async showEditParamsDialog(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          params: { attr_sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('修改参数错误')
      }
      console.log(res)
      this.editParamsForm = res.data
      this.editDialogVisible = true
    },
    // 监听编辑对话框的关闭
    editParamsClosed() {
      this.$refs.editParamsFormRef.resetFields()
    },
    // 点击确定完成修改操座
    editParamsDate() {
      this.$refs.editParamsFormRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) {
          this.$message.error('修改参数错误')
        }
        console.log(res)
        this.$message.success('修改成功')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    // 删除属性
    async removeParamsById(attrId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该属性, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      if (res.meta.status !== 200) {
        this.$message.error('删除商品分类失败')
      }
      this.$message.success('删除商品分类成功')
      this.getParamsData()
    },
    // 向服务器发送请求更新数据
    async updataAttrVal (row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' '),
        }
      )
      if (res.meta.status !== 200) {
        this.$message.error('修改属性失败')
      }
      console.log(res)
      this.$message.success('修改属性成功')
    },
    // 处理文本框失去焦点或者按下enter文件
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      // 合法的输入进行添加tag标签
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求将数据添加到数据库中
      this.updataAttrVal(row)
    },
    showInput (row) {
      row.inputVisible = true
      // 文本框自动获取焦点
      /** 当布尔值改变后dom元素还未被渲染此时调用focus会报错，执行$nextTick会解决这个错误 */
      // $nextTick当页面上元素被重新渲染之后，会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除tag标签
    handleTagClosed(index, row) {
      row.attr_vals.splice(index, 1)
      // 更新删除的数据在数据库
      this.updataAttrVal(row)
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 根据是否选中该表button的可用性
    isbtnDisable() {
      if (this.selectedCates.length !== 3) {
        return true
      }
      return false
    },
    // 当前选中的三级标签的id
    cateId() {
      if (this.selectedCates.length === 3) {
        return this.selectedCates[2]
      }
      return null
    },
  },
}
</script>

<style scoped>
.catopt {
  margin: 15px 0;
}
.cascader {
  width: 280px !important;
}
.input-new-tag {
  width: 120px;
}
</style>
